package com.zheng.controller;

import com.alibaba.fastjson.JSON;
import com.zheng.mapper.UserMapper;
import com.zheng.pojo.QueryInfo;
import com.zheng.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
@Api("用户信息类")
@RestController
public class UserController {
    @Autowired
    UserMapper userMapper;
    /*解决跨域问题*/
    @CrossOrigin
    @ApiOperation("模糊查询")
    @GetMapping("/allUser")
    public String getUserList(@RequestBody QueryInfo queryInfo){
        System.out.println(queryInfo);
        int numbers = userMapper.getUserCounts("%"+queryInfo.getQuery()+"%");// 获取数据总数
        int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();
        List<User> users = userMapper.getAllUser("%"+queryInfo.getQuery()+"%",pageStart,queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("data",users);
        System.out.println("总条数："+numbers);
        String users_json = JSON.toJSONString(res);
        return users_json;
    }
    @CrossOrigin
    @ApiOperation("修改用户信息")
    @PutMapping("/userState")
    public String updateUserState(@RequestParam("id") Integer  id,
                                  @RequestParam("state") Boolean state){
        int i = userMapper.updateState(id, state);
        System.out.println("用户编号:"+id);
        System.out.println("用户状态:"+state);
        String str = i >0?"success":"error";
        return str;
    }
    @CrossOrigin
    /*添加用户*/
    @ApiOperation("添加用户")
    @PostMapping("/addUser")
    public String addUser(@RequestBody User user){
        System.out.println(user);
        user.setRole("普通用户");
        user.setState(false);
        int i = userMapper.addUser(user);
        //如果成功，数据添加成功则返回success，否则error
        String str = i >0?"success":"error";
        return str;
    }
    @CrossOrigin
    /*获取修改用户信息后的信息*/
    @ApiOperation("获取更新后数据")
    @GetMapping("/getUpdate")
    public String getUpdateUser(int id){
        System.out.println("编号:"+id);
        User updateUser = userMapper.getUpdateUser(id);
        String users_json = JSON.toJSONString(updateUser);
        return users_json;
    }
    @CrossOrigin
    @ApiOperation("修改用户信息")
    @GetMapping("/editUser")
    public String editUser(@RequestBody User user){
        System.out.println(user);
        int i = userMapper.editUser(user);
        String str = i >0?"success":"error";
        return str;
    }
    @CrossOrigin
    @ApiOperation("删除用户")
    @DeleteMapping("/deleteUser")
    public String deleteUser(int id){
        System.out.println(id);
        int i = userMapper.deleteUser(id);
        System.out.println("删除成功！");
        String str = i >0?"success":"error";
        return str;
    }
}
